const path = require('path')
const gulp = require('gulp')
const less = require('gulp-less')
const babel = require('gulp-babel')
const ts = require('gulp-typescript')
const del = require('del')
const tsconfig = require('./tsconfig.json')

// 删除lib下所有文件
function clean() {
  return del('./lib/**')
}

// 构建样式
function buildStyle() {
  return gulp.src(['./src/**/*.less'], {
    base: './src/'
  }).pipe(
    less({
      paths: [path.join(__dirname, 'src')],
      relativeUrls: true,
    })
  ).pipe(gulp.dest('./lib'));
}

// 拷贝静态资源
function copyAssets() {
  return gulp
    .src('./src/assets/**/*')
    .pipe(gulp.dest('lib/assets'))
}

// 构建es
function buildES() {
  const tsProject = ts({
    ...tsconfig.compilerOptions,
    module: 'ESNext',
  })
  return gulp
    .src(['src/**/*.{ts,tsx}'])
    .pipe(tsProject)
    .pipe(babel())
    .pipe(gulp.dest('lib/'))
}

// 构建声明文件
function buildDeclaration() {
  const tsProject = ts({
    ...tsconfig.compilerOptions,
    declaration: true,
    emitDeclarationOnly: true
  })
  return gulp
    .src(['src/**/*.{ts,tsx}'])
    .pipe(tsProject)
    .pipe(gulp.dest('lib/types/'))
}

// 执行构建任务
exports.default = gulp.series(
  clean,
  buildES,
  gulp.parallel(buildDeclaration, buildStyle),
  copyAssets
)
